import {createRouter, createWebHistory} from 'vue-router'
import LoginView from '@/views/LoginView.vue'
import useUserStore from '@/stores/modules/user'
import {to as tos} from 'await-to-js'
import {showNotify} from 'vant'
import {getParameterByName, getSessionStorageItem, isWeChat, setSessionStorageItem} from '@/utils/common'
import {getWechatOpenId} from '@/api/jdb'
import {getToken} from '@/utils/auth.js';

const router = createRouter({
  // scrollBehavior (to, from, savedPosition) {
  //   return { x: 0, y: 0 }
  // },
  scrollBehavior(to, from, savedPosition) {
    if (savedPosition) {
      return savedPosition;
    } else {
      return {top: 0};
    }
  },
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '',
      redirect: '/index',
      // component: () => import('@/views/IndexView.vue'),
      meta: {
        needAuth: true,
        needOpenId: true,
      },
    },
    {
      path: '/login',
      name: 'login',
      component: LoginView,
      meta: {
        needAuth: false,
        needOpenId: true,
        title: '登录'
      },
    },
    {
      path: "/:pathMatch(.*)*",
      name: "error",
      component: () => import("@/views/ErrorView.vue"),
      meta: {
        needAuth: false,
        needOpenId: false,
      },
    },
    {
      path: '/success',
      name: 'success',
      // route level code-splitting
      // this generates a separate chunk (About.[hash].js) for this route
      // which is lazy-loaded when the route is visited.
      component: () => import("@/views/SuccessView.vue"),
      meta: {
        needAuth: false,
        needOpenId: false,
      },
    },
    {
      path: '/index',
      name: 'index',
      // route level code-splitting
      // this generates a separate chunk (About.[hash].js) for this route
      // which is lazy-loaded when the route is visited.
      component: () => import('@/views/IndexView.vue'),
      meta: {
        needAuth: true,
        needOpenId: true,
        title: '会员中心',
      },
    },
    {
      path: '/student-register',
      name: 'studentRegister',
      // route level code-splitting
      // this generates a separate chunk (About.[hash].js) for this route
      // which is lazy-loaded when the route is visited.
      component: () => import('@/views/StudentRegisterView.vue'),
      meta: {
        needAuth: false,
        needOpenId: false,
        title: '题少易懂,不过补偿'
      },
    },
    {
      path: '/share',
      name: 'share',
      // route level code-splitting
      // this generates a separate chunk (About.[hash].js) for this route
      // which is lazy-loaded when the route is visited.
      component: () => import('@/views/ShareView.vue'),
      meta: {
        needAuth: false,
        needOpenId: false,
        title: '驾多宝，题少易懂，不过补偿',
      },
    },
    {
      path: '/bind-qr-code',
      name: 'bindQrCode',
      // route level code-splitting
      // this generates a separate chunk (About.[hash].js) for this route
      // which is lazy-loaded when the route is visited.
      component: () => import('@/views/BindQrCodeView.vue'),
      meta: {
        needAuth: false,
        needOpenId: false,
        title: '绑定二维码，成为分销商',
      },
    },
    {
      path: '/qr-code',
      name: 'qrCode',
      // route level code-splitting
      // this generates a separate chunk (About.[hash].js) for this route
      // which is lazy-loaded when the route is visited.
      component: () => import('@/views/QrCodeView.vue'),
      meta: {
        needAuth: true,
        needOpenId: true,
      },
    },
    {
      path: '/invite-next-level',
      name: 'inviteNextLevel',
      // route level code-splitting
      // this generates a separate chunk (About.[hash].js) for this route
      // which is lazy-loaded when the route is visited.
      component: () => import('@/views/InviteNextLevelView.vue'),
      meta: {
        needAuth: true,
        needOpenId: true,
        title: '加入驾多宝，工资涨不停',
      },
    },
    {
      path: '/we-chat-service-account',
      name: 'weChatServiceAccount',
      // route level code-splitting
      // this generates a separate chunk (About.[hash].js) for this route
      // which is lazy-loaded when the route is visited.
      component: () => import('@/views/WeChat/ServiceAccountView.vue'),
      meta: {
        needAuth: false,
        needOpenId: false,
        title: '关注公众号',
      },
    },
    //原项目微信消息跳转至新项目地址
    {
      path: '/jkjlfx/api/gongzhonghao/fzxiaji',
      redirect: '/we-chat-service-account-msg-bridge',
    },
    {
      path: '/we-chat-service-account-msg-bridge',
      name: 'weChatServiceAccountMsgBridge',
      // route level code-splitting
      // this generates a separate chunk (About.[hash].js) for this route
      // which is lazy-loaded when the route is visited.
      component: () => import('@/views/WeChat/ServiceAccountMsgBridgeView.vue'),
      meta: {
        needAuth: false,
        needOpenId: false,
      },
    },
    // {
    //   path: '/recruitment-material',
    //   name: 'recruitmentMaterial',
    //   // route level code-splitting
    //   // this generates a separate chunk (About.[hash].js) for this route
    //   // which is lazy-loaded when the route is visited.
    //   component: () => import('@/views/DailyPoster/RecruitmentMaterialView.vue'),
    //   meta: {
    //     needAuth: true,
    //     needOpenId: true,
    //     keepAlive: true,
    //     title: '招生素材',
    //   },
    // },
    // {
    //   path: '/recruitment-material-list',
    //   name: 'recruitmentMaterialList',
    //   // route level code-splitting
    //   // this generates a separate chunk (About.[hash].js) for this route
    //   // which is lazy-loaded when the route is visited.
    //   component: () => import('@/views/DailyPoster/RecruitmentMaterialListView.vue'),
    //   meta: {
    //     needAuth: true,
    //     needOpenId: true,
    //     keepAlive: true,
    //     title: '招生素材',
    //   },
    // },
    // {
    //   path: '/daily-poster',
    //   name: 'dailyPoster',
    //   // route level code-splitting
    //   // this generates a separate chunk (About.[hash].js) for this route
    //   // which is lazy-loaded when the route is visited.
    //   component: () => import('@/views/DailyPoster/DailyPosterView.vue'),
    //   meta: {
    //     needAuth: true,
    //     needOpenId: true,
    //     keepAlive: true,
    //     title: '海报',
    //   },
    // },
    // {
    //   path: '/poster-content',
    //   name: 'posterContent',
    //   // route level code-splitting
    //   // this generates a separate chunk (About.[hash].js) for this route
    //   // which is lazy-loaded when the route is visited.
    //   component: () => import('@/views/DailyPoster/PosterContentView.vue'),
    //   meta: {
    //     needAuth: true,
    //     needOpenId: true,
    //     title: '海报',
    //   },
    // },
    {
      path: '/team',
      name: 'team',
      // route level code-splitting
      // this generates a separate chunk (About.[hash].js) for this route
      // which is lazy-loaded when the route is visited.
      component: () => import('@/views/Team/TeamIndexView.vue'),
      meta: {
        needAuth: true,
        needOpenId: true,
        title: '我的团队',
      },
    },
    {
      path: '/withdraw',
      name: 'withdraw',
      // route level code-splitting
      // this generates a separate chunk (About.[hash].js) for this route
      // which is lazy-loaded when the route is visited.
      component: () => import('@/views/Withdraw/WithdrawIndexView.vue'),
      meta: {
        needAuth: true,
        needOpenId: true,
      },
    },
    {
      path: '/withdraw-history',
      name: 'withdrawHistory',
      // route level code-splitting
      // this generates a separate chunk (About.[hash].js) for this route
      // which is lazy-loaded when the route is visited.
      component: () => import('@/views/Withdraw/WithdrawHistoryView.vue'),
      meta: {
        needAuth: true,
        needOpenId: true,
        title: '提现记录'
      },
    },
    //原项目分销二维码地址跳转至新项目分销二维码地址
    {
      path: '/jkjlfx/api/gongzhonghao/fenxiang',
      redirect: to => {
        // 将原路由中的 query 参数传递到 /g 路由
        return {path: '/invite-qrcode', query: to.query}
      }
    },
    {
      path: '/invite-qrcode',
      name: 'inviteQrcode',
      // route level code-splitting
      // this generates a separate chunk (About.[hash].js) for this route
      // which is lazy-loaded when the route is visited.
      component: () => import('@/views/InviteQrcodeView.vue'),
      meta: {
        needAuth: false,
        needOpenId: false,
      },
    },
    {
      path: '/vip',
      name: 'vip',
      // route level code-splitting
      // this generates a separate chunk (About.[hash].js) for this route
      // which is lazy-loaded when the route is visited.
      component: () => import('@/views/VipView.vue'),
      meta: {
        needAuth: true,
        needOpenId: true,
      },
    },
    {
      path: '/withdraw-pay',
      name: 'withdrawPay',
      // route level code-splitting
      // this generates a separate chunk (About.[hash].js) for this route
      // which is lazy-loaded when the route is visited.
      component: () => import('@/views/Withdraw/WithdrawPay.vue'),
      meta: {
        needAuth: false,
        needOpenId: false,
      },
    },
    {
      path: '/withdraw-pay-success',
      name: 'withdrawPaySuccess',
      // route level code-splitting
      // this generates a separate chunk (About.[hash].js) for this route
      // which is lazy-loaded when the route is visited.
      component: () => import('@/views/Withdraw/WithdrawPaySuccess.vue'),
      meta: {
        needAuth: false,
        needOpenId: false,
      },
    },
    // {
    //   path: '/jl-school-machine',
    //   name: 'jlSchoolMachine',
    //   component: () => import('@/views/JLSchool/JLSchool.vue'),
    //   meta: {
    //     needAuth: false,
    //     needOpenId: false,
    //     needMachinePermission: true,
    //     title: '获取注册码',
    //   },
    // },
  ],
})
router.beforeEach(async (to, from, next) => {
  const {title} = to.meta;

  document.title = title || import.meta.env.VITE_APP_TITLE
  // const { title, description } = to.meta;
  //
  // const defaultDescription = 'Default Description';
  // const descriptionElement = document.querySelector('head meta[name="description"]')
  //
  // descriptionElement.setAttribute('content', description || defaultDescription)
  if (isWeChat() && to.meta.hasOwnProperty('needOpenId') && to.meta.needOpenId) {
    let openId = getSessionStorageItem("openId");
    if (!openId) {
      let code = getParameterByName("code", window.location.href)
      // console.info(code, "获取url中code参数")
      if (!!code) {
        const [err, response] = await tos(getWechatOpenId({code: code}))
        if (err) {
          showNotify({type: "danger", message: err, duration: 5 * 1000})
          next({path: '/login'})
        } else {
          setSessionStorageItem("openId", response.data.openid)
          next({path: to.path, replace: true, params: to.params, query: to.query, hash: to.hash, name: to.name})
        }
        return
      }
      next(false)
      const redirectUri = encodeURIComponent(window.location.href)
      const appId = `${import.meta.env.VITE_WE_CHAT_APP_ID}`
      let authUrl = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appId}&redirect_uri=${redirectUri}&response_type=code&scope=snsapi_base#wechat_redirect`
      // console.info(authUrl, "获取微信code路径")
      window.location.replace(authUrl)
      return
    }
  }
  if (to.path === '/login') {
    if (getToken()) {
      next({path: '/'})
      return
    }
  }
  if (to.meta.hasOwnProperty('needAuth') && to.meta.needAuth) {
    if (!useUserStore().userId) {
      //如果当前store中无用户id， 调用接口获取用户登录信息
      const [err] = await tos(useUserStore().getInfo())
      if (err) {
        await useUserStore().logout()
        showNotify({type: "danger", message: err, duration: 5 * 1000})
        next({path: '/login'})
      } else {
        next({path: to.path, replace: true, params: to.params, query: to.query, hash: to.hash, name: to.name})
      }
      return
    }
  }
  if (to.meta.hasOwnProperty('needMachinePermission') && to.meta.needMachinePermission) {
    if (!useUserStore().userId) {
      //如果当前store中无用户id， 调用接口获取用户登录信息
      const [err] = await tos(useUserStore().getInfo())
      if (err) {
        setSessionStorageItem("machine-url", window.location.href);
        await useUserStore().logout()
        showNotify({type: "danger", message: err, duration: 5 * 1000})
        next({path: '/login'})
      } else {
        if (!useUserStore().schoolName || useUserStore().schoolName !== '1') {
          showNotify({type: "danger", message: "用户没有获取注册码权限", duration: 5 * 1000})
          next({path: '/login'})
          return;
        }
        next({path: to.path, replace: true, params: to.params, query: to.query, hash: to.hash, name: to.name})
      }
      return
    } else {
      if (!!useUserStore().schoolName && useUserStore().schoolName !== '1') {
        showNotify({type: "danger", message: "用户没有获取注册码权限", duration: 5 * 1000})
        return
      }
    }
  }
  next()
})

export default router
